//
//  AppSettings.swift
//  Wallet
//
//  Created by Julian on 2022/5/7.
//

import Foundation
import RxSwift
import RxCocoa

enum CurrencyType: String {
    case USD // default
    case HKD
}

struct PreferenceKey {
    static let currency_display = "currency_display"
}

struct AppSettings {
    // MARK: - DATA
    public var currencyValue: CurrencyType {
        if let value = UserDefaults().value(forKey: PreferenceKey.currency_display) as? String {
            return CurrencyType.init(rawValue: value) ?? CurrencyType.USD
        } else {
            return CurrencyType.USD
        }
    }
    static let shared = AppSettings()
    private let bag = DisposeBag()
    
    // MARK: - STATE
    public var currency: BehaviorSubject<CurrencyType> = BehaviorSubject(value: CurrencyType.USD)
    
    // MAKR: - INITIALIZE
    private init() {
        currency.onNext(currencyValue)
    }
}


//@propertyWrapper
//struct ExchangeCurrencyWrapper {
//    let currency: CurrencyType = AppSettings.shared.currency
//    private let coin: Coin
//
//    init(coin: Coin) {
//        self.coin = coin
//    }
//
//    var wrappedValue: Double {
//        get {
//            switch self.currency {
//            case .HKD:
//                return 1.9
//            default:
//                return 1.2
//            }
//        }
//    }
//}

@propertyWrapper
struct UserDefaultsWrapper<T> {
    let key: String
    let defaultValue: T
    var storage: UserDefaults = .standard
    
    var wrappedValue: T {
        get {
            storage.value(forKey: key) as? T ?? defaultValue
        }
        set {
            storage.setValue(newValue, forKey: key)
        }
    }
}
